import { StateMachineEvent } from './type';

export class Listeners {
    private listeners: Map<
        string,
        ((event: StateMachineEvent) => void)[]
    > = new Map();

    /**
     * 添加事件监听器
     */
    addEventListener(
        eventType: string,
        listener: (event: StateMachineEvent) => void,
    ): void {
        if (!this.listeners.has(eventType)) {
            this.listeners.set(eventType, []);
        }
        this.listeners.get(eventType)!.push(listener);
    }

    /**
     * 移除事件监听器
     */
    removeEventListener(
        eventType: string,
        listener: (event: StateMachineEvent) => void,
    ): void {
        const listeners = this.listeners.get(eventType);
        if (listeners) {
            const index = listeners.indexOf(listener);
            if (index > -1) {
                listeners.splice(index, 1);
            }
        }
    }

    /**
     * 通知监听器
     */
    notifyListeners(event: StateMachineEvent): void {
        const listeners = this.listeners.get(event.type) || [];
        listeners.forEach((listener) => listener(event));
    }
}
